<template>
	<view>
		<u-navbar :is-back="false" :bgColor="`rgba(256,256,256,${navBgOpacity})`" back-icon-color="#fff"
			:border-bottom="false">
			<template #left>
				<view class="flex nav">
					<image src="../../static/images/logo.png" class="self-center" style="width: 50rpx;height: 50rpx;">
					</image>
					<view class="ml5 ">
						<view class="search-box">
							<view class="left  flex" @click="$u.throttle(route('/pages/gas_station_mall/select_area/index'), 500)">
								<text class="city">{{location.city}}</text>
								<text class="custom-icon-xiajiantou-copy custom-icon icon"></text>
							</view>
							<text class="fenge"></text>
							<view class="right" @click="$u.throttle(route('/pages/gas_station_mall/search/index'), 500)">
								请输入加油站名称
							</view>
						</view>
					</view>
				</view>
			</template>
		</u-navbar>
		<u-swiper :list="swiperList" :indicator="true" height="400rpx" :radius="0" @click="swiperFun"
			keyName='adImage'></u-swiper>
	</view>
	<!-- #ifdef MP-WEIXIN -->
	<u-sticky :offset-top="(statusBarHeight + 44)">
	<!-- #endif -->
		<!-- #ifdef !MP-WEIXIN -->
		<u-sticky>
		<!-- #endif -->
			<view class=" " style="background-color: #fff;">
				<u-tabs :list="tabList" lineWidth="50" :current="current" :scrollable="false" lineColor="#FF4110"
					:activeStyle="{
						color: '#FF4110',
						fontWeight: 'bold',
						transform: 'scale(1.05)'
					}" @click="tabChange"></u-tabs>
				<le-dropdown :isBold=" true" v-model:menuList="menuList" themeColor="#FF4110" bgColor="#fff"
					:duration="300" :isCeiling="false" @onConfirm="onConfirm"></le-dropdown>
			</view>
		</u-sticky>
		<!-- 列表 -->
		<scroll-view class="w94 " scroll-y style="height: 60vh;" @scrolltolower="loadMore">
			<view class="tip" v-if="current==2">
				<!-- <text>免费加油提示</text> -->
				<text>免费加油需要同意协议哦！</text>
			</view>
			<view class="listNull" v-if="gasList.length == 0">
				<img src="@/static/images/listNull.png" alt="" />
				<text>暂无数据</text>
			</view>
			<GasStaionItem v-for="(item,index) in gasList" :key="index" :list="item" :isFree="item.freeSettings.length" />
			<!-- 加载状态 -->
			<u-loadmore :status="loadingState" icon-type="circle" />
		</scroll-view>
		<!-- 分页控件 -->
		<u-pagination v-model="page" :page-count="pageCount" :total="pageTotal" mode="button" @change="pageChange" />

		<TabBar :tabValue="0" />

		<!-- 优惠活动弹框 -->
		<u-popup :show="activityShow" @close="closeActivityShow" mode="center" round='8'>
			<view class="activityShow">
				<view class="bg">
					<image src="/static/images/bg2.png" alt="" />
				</view>
				<text style="font-size: 40rpx;margin: 15rpx 0;color: #fff;z-index: 1;">优惠活动</text>

				<view class="header" style="min-height: 10vh;padding:0;z-index: 1;">
					<view class="activityList flex flex-wrap">
						<!-- <view class="list-item" v-for="(item,index) in list" :key="index" @click="clickComment(item)">
						{{item.title}}({{item.num}})
					</view> -->
						<image :src="activityInfo.adImage" mode="" ></image>
						<image style="margin-top: 30rpx;" :src="activityInfo.conetxtImage" mode=""></image>
					</view>
				</view>
					<view class="card-item" v-if="isHave && +new Date(activityInfo.endTime)>+new Date()"  @click="activityFun">
						<!-- 有效期内则显示  v-if="+new Date(activityInfo.endTime)>+new Date()" -->
						<view class="card">
							<view class="three ">
								<view class="left flex-center">
									<text style="font-size: 32rpx;" v-if="activityInfo.ctype=='满减券'">{{'满'+activityInfo.fullAmount+'-'+activityInfo.amount}}</text>
									<text style="font-size: 32rpx;" v-else-if="activityInfo.ctype=='折扣券'">{{activityInfo.cardDisc}}折</text>
									<text style="font-size: 32rpx;" v-else>￥{{activityInfo.amount}}元代金券</text>
								</view>
								<view class="right">
									<image src="@/static/images/coupon-r.png" style="100%"></image>
									<view class="text ">
										<view>
											<!-- <view class="title" v-if="activityInfo.ctype=='抵扣券'">无门槛抵扣</view>
											<view class="title" v-else>满{{activityInfo.fullAmount}}元可用</view> -->
											<view class="title">
												限{{'<'+activityInfo.stationInfo.name+'>'}}使用
											</view>
											<view class="mt5 flex sub-title">
												<view class="item">
													有效期至：{{activityInfo.endTime}}
												</view>
											</view>
										</view>
										<image src="@/static/images/coupon-r-2.png"
											style="width: 80rpx;height: 80rpx;margin-left: 10rpx;"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="listNull" v-else>
						<img src="@/static/images/listNull.png" alt="" />
						<text>暂无优惠券</text>
					</view>
				<!-- <u-button shape="circle" type="primary" text="领取优惠券" @click="activityFun"></u-button> -->
			</view>
		</u-popup>
</template>

<script setup>
	import API from "@/api/index.js"
	import TabBar from "@/components/tabbar/index.vue"
	import GasStaionItem from "@/components/gas_station_item/index.vue"
	import {
		nextTick,
		reactive,
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPageScroll,
		onReachBottom,
		onShareAppMessage
	} from '@dcloudio/uni-app';

	import {
		route
	} from '@/uni_modules/uview-plus';
	import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
	import {
		DropdownList
	} from "./data.js";
	import {
		useAppStore,
		useUserStore
	} from "@/store/index.js"
	import {
		storeToRefs
	} from "pinia"
	import radio from "../../uni_modules/uview-plus/components/u-radio/radio.js";
	const {
		location
	} = storeToRefs(useAppStore())
	const {
		userInfo
	} = storeToRefs(useUserStore())
	// 自动响应式检查
	onMounted(() => {
		// 监听全局事件
		uni.$on('locationUpdated', (data) => {
			console.log("data", data);
			uni.setStorageSync('locationUpdated',true)
			if (data.city) {
				getList(1)
			}
		})
	})
	// 计算总页数
	const pageCount = computed(() => {
		return Math.ceil(pageTotal.value / pageSize.value)
	})
	let activityShow = ref(false)
	let activityInfo = ref({})
	let isHave = ref(false)
	let page = ref(1)
	let pageSize = ref(10)
	let pageTotal = ref(10)
	let loading = ref(false)
	let loadingState = ref('loadmore')
	const city = ref('')
	onShow(() => {
		uni.$on('city', (data) => {
			console.log("city", data.name);
			city.value = data.name
			getList(1, [{
				"filedIndex": "c",
				"filedValue": data.name
			}])
		})
		uni.hideTabBar()
	})
	onLoad(() => {
		// 判断是哪一类型的用户,跳转相应链接,如果没登录就是普通用户
		if (userInfo.value.type == 1) {
			uni.reLaunch({
				url: '/pages/merchant_center/index/index'
			})
		}
		// 获取轮播图列表
		getActivityList()
		if (uni.getStorageSync('locationUpdated')) {
			getList(1)
		}
	})
	// 当前页index
	let pageIndex = ref(1)
	// 排序方式 0,智能排序 1,价格排序 2,距离排序
	let bySort = ref(0)
	// 筛选条件
	let fileds = reactive([{
		"filedIndex": "c",
		// "filedValue": city.value ? city.value : uni.getStorageSync('location').city
		"filedValue": '阿坝'
	}])
	const getList = async (pageIndex) => {
		// 处理中fileds中为null的数据
		const filteredArray = fileds.filter(item => item !== null);
		try {
			loadingState.value = 'loading'
			let {
				data
			} = await API.list({
				"pageIndex": pageIndex,
				"pageSize": 10,
				"bySort": bySort.value || 0,
				"earth": {
					"lat": uni.getStorageSync('location').lat,
					"lng": uni.getStorageSync('location').lng
				},
				"fileds": filteredArray
			})
			if (pageIndex == 1) {
				gasList.length=0
				gasList.value = data.list
			} else {
				gasList.value = [...gasList.value, ...data.list]
			}
			pageTotal.value = data.total
			page.value = data.currentPage
			loadingState.value = couponList.length >= pageTotal.value ? 'nomore' : 'loadmore'
			// if (data.list.length != 0) {
			// 	gasList.value = data.list
			// }
		} catch (e) {
			loadingState.value = 'error'
		}
	}

	// 小程序状态栏高度
	// const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight)
	const statusBarHeight = ref(uni.getWindowInfo().statusBarHeight)

	/* 下拉列表 */
	const dataList = ref([]);
	//请求参数
	const params = ref({});

	let gasList = ref([])


	// 页码变化
	const pageChange = (page) => {
		page.value = page
		console.log("页码变化了", page.value);
		getList(page.value)
	}
	// 加载更多（滚动到底部）
	const loadMore = () => {
		console.log("滚动到底了");
		console.log(page.value, pageCount.value);
		if (page.value < pageCount.value) {
			page.value++
			setTimeout(() => {
				getList(page.value)
			}, 1000)
		}
	}
	/* 轮播图 */
	const swiperList = reactive([])
	// 获取轮播图
	const getActivityList = async () => {
		let res = await API.ActivityList({
			"pageIndex": 1,
			"pageSize": 10,
			"condition": [{
				"filedIndex": "string",
				"filedValue": "string"
			}]
		})
		console.log("getActivityList", res);
		Object.assign(swiperList, res.data.list)
	}
	// 关闭优惠活动弹窗
	const closeActivityShow = () => {
		activityShow.value = false
		activityInfo.value = {}
		isHave.value = false
		// rate.value = 0
	}
	// 领取活动优惠券
	const activityFun = async () => {
		console.log("领取活动优惠券", activityInfo.value);
		let id = await API.uuid()
		let userInfo = uni.getStorageSync('userInfo')
		let res = await API.UserCoupon({
			// 后台修改信息 必要字段------------------
			Id: id.data,
			RegisterUserId: userInfo.id,
			RegisterDeptId: userInfo.deptId,
			RegisteTime: userInfo.registeTime,
			editUserId:userInfo.id,
			EditTime:  +new Date(),
			UserId: userInfo.id,
			// ---------------------------
			// id: item.id,
			id: '',
			CouponId: activityInfo.value.id,
			"name": activityInfo.value.name,
			"ctype": activityInfo.value.ctype,
			"state": activityInfo.value.state ? 1 : 0,
			"cardDisc": activityInfo.value.cardDisc,
			"fullAmount": activityInfo.value.fullAmount,
			"stationId": activityInfo.value.stationId,
		})
		console.log("领取优惠券 res", res);
		if (res.code == 1) {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		} else {
			uni.showToast({
				title: "您已经领取过一次了！",
				icon: 'none'
			})
		}
		activityShow.value = false
	}
	// 点击轮播图
	const swiperFun =async (index) => {
		activityShow.value = true
		console.log("当前轮播图 index", index, swiperList[index].couponId.toString());
		let res = await API.couponDetail(swiperList[index].couponId.toString())
		// let res = await API.couponDetail('00a20dbf9a934903a32221f3f5af7bed')
		// activityInfo.value = res.data
		if(res.data){
			isHave.value = true
			activityInfo.value = {...swiperList[index],...res.data}
		}else{
			isHave.value = false
			activityInfo.value = swiperList[index]
		}
		// 跳转前设置全局变量
		// getApp().globalData.tabParams = { id: '00a20dbf9a934903a32221f3f5af7bed' };
		
		console.log("activityInfo.value",activityInfo.value);
	}

	/* tab */
	const tabList = ref(
		[{
				name: '全部'
			},
			{
				name: '供应保障'
			},
			{
				name: '免费加油'
			},
		])
	//当前的tab
	const current = ref(0);
	//点击tab事件
	const tabChange = (item) => {
		console.log("tabChange item", item, fileds, "111");
		current.value = item.index;
		gasList.value.length = 0
		if (city.value) {
			fileds[0] = {
				"filedIndex": "c",
				"filedValue": city.value
			}
		}
		// let shai = []
		if (item.index == 0) {
			// Object.assign(fileds, [{
			// 	"filedIndex": "c",
			// 	"filedValue": city.value ? city.value : uni.getStorageSync('location').city
			// }])
			fileds[3] = null
			getList(1)
		} else if (item.index == 1) {
			fileds[3] = {
				"filedIndex": "isQa",
				"filedValue": 'true'
			}
			getList(1)
		} else if (item.index == 2) {
			fileds[3] = {
				"filedIndex": "free",
				"filedValue": 'true'
			}
			getList(1)
		}
		// getMescroll().resetUpScroll();
	};


	/* 筛选 */
	const menuList = ref(DropdownList)
	// 单项筛选
	// const onConfirm = (data, id) => {
	// 	console.log("data,id", data, id);
	// 	bySort.value = data.value
	// 	fileds = []
	// 	fileds.splice(0, fileds.length);
	// 	if (id == 0) {
	// 		// 排序方式
	// 		getList(1, data.value)
	// 	} else if (id == 1) {
	// 		// 规格选择
	// 		fileds.push({
	// 			"filedIndex": "spec",
	// 			"filedValue": data.children[0].value
	// 		})
	// 		getList(1, 0, fileds)
	// 	} else {
	// 		// 品牌选择
	// 		fileds.push({
	// 			"filedIndex": "brandn",
	// 			"filedValue": data.children[0].value
	// 		})
	// 		getList(1, 0, fileds)
	// 	}
	// 	console.log("fileds", fileds);
	// }
	// let arr=reactive([])
	// 多项筛选
	const onConfirm = (data, id) => {
		gasList.value.length = 0
		console.log("data,id", data, id);
		if (city.value) {
			fileds[0] = {
				"filedIndex": "c",
				"filedValue": city.value
			}
		}
		if (id == 0) {
			// 排序方式
			bySort.value = data.value
			console.log("city", city.value);

			// getList(1,data.value)
		} else if (id == 1) {
			// 规格选择
			fileds[1] = {
				"filedIndex": "spc",
				"filedValue": data.children[0].value?.toString() || null
			}
			// getList(1,0,fileds)
		} else {
			// 品牌选择
			fileds[2] = {
				"filedIndex": "B",
				"filedValue": data.children[0].value?.toString() || null
			}
		}
		// 筛选时，默认从第一页列表开始
		getList(1)
		console.log("fileds push ", bySort.value, fileds);
	}

	/* 滚动监听 */
	const navBgOpacity = ref(0) // nav透明度
	onPageScroll(({
		scrollTop
	}) => {
		if (scrollTop <= 44) {
			// 当滚动距离小于或等于44px时，根据滚动距离计算透明度
			navBgOpacity.value = scrollTop / 44;
		} else {
			// 当滚动距离大于44px时，透明度设置为100%
			navBgOpacity.value = 1;
		}
	})
</script>

<style lang="scss" scoped>
	.card-item {
		position: relative;
		margin-top: 20rpx;
	
		.card {
			// background-image: radial-gradient(circle at 276px top, #f5f5f5, #f5f5f5 5px, transparent 6px), radial-gradient(circle at 276px bottom, #f5f5f5, #f5f5f5 5px, transparent 6px);
			position: relative;
			padding: 5rpx;
			border-radius: 13px;
			background-color: #fff;
	
	
			.address {
				background-color: #FAFAFA;
				padding: 10rpx 16rpx;
				font-size: 12px;
				border-radius: 20px;
				font-weight: 800;
			}
	
			.three {
				margin-top: 20rpx;
				background: $u-primary;
				position: relative;
				height: 150rpx;
				border-radius: 25rpx;
				display: flex;
				align-items: center;
	
				.left {
					height: 85%;
					width: 200rpx;
					background: url('@/static/images/coupon-l.png');
					background-size: cover;
					font-size: 30px;
					font-weight: 800;
					color: #DC2B2A;
				}
	
				.right {
					position: absolute;
					right: 0;
					height: 100%;
					width: 500rpx;
	
					image {
						width: 100%;
						height: 100%;
					}
	
					.text {
						position: absolute;
						top: 0;
						width: 100%;
						height: 100%;
						text-align: center;
						display: flex;
						align-items: center;
						justify-content: center;
					}
	
					.title {
						font-size: 16px;
						font-weight: 600;
						color: #fff;
					}
	
					.sub-title {
						.item {
							font-size: 12px;
							padding: 0 10rpx;
							color: #fff;
	
							&~.item {
								position: relative;
	
								&:before {
									content: '';
									position: absolute;
									width: 1rpx;
									height: 22rpx;
									top: 55%;
									margin-top: -12rpx;
									background-color: #fff;
									left: 0;
								}
							}
						}
					}
				}
	
	
	
			}
	
			.four {}
		}
	}
	
	.activityList {
		flex-direction: column;
		margin-top:60rpx;

		image {
			border-radius: 12rpx;
			width: 650rpx;
			height: 350rpx;
			margin: 10rpx auto;
		}
	}

	.activityShow {
		position: relative;
		// background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		width: 90vw;
		height: 70vh;
		padding: 20rpx;
		text-align: center;
		.bg{
			position: absolute;
			top:0;
			left:0;
			image{
				    width: 716rpx;
				    height: 150rpx;
			}
		}
		.right {
			position: absolute;
			right: 0;
			height: 100%;
			width: 470rpx;

			image {
				width: 100%;
				height: 100%;
			}

			.text {
				position: absolute;
				top: 0;
				width: 100%;
				height: 100%;
				text-align: center;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.title {
				font-size: 16px;
				font-weight: 600;
				color: #fff;
			}

			.sub-title {
				.item {
					font-size: 12px;
					padding: 0 10rpx;
					color: #fff;

					&~.item {
						position: relative;

						&:before {
							content: '';
							position: absolute;
							width: 1rpx;
							height: 22rpx;
							top: 55%;
							margin-top: -12rpx;
							background-color: #fff;
							left: 0;
						}
					}
				}
			}
		}
	}

	.listNull {
		display: flex;
		flex-direction: column;
		text-align: center;
		margin: 0 auto;

		image {
			width: 200rpx;
			height: 200rpx;
			// margin: 10% 0 10% 10%;
			margin: 20rpx auto;
		}

		text {
			color: #919ea9;
		}
	}

	.tip {
		display: flex;
		flex-direction: column;
		width: 100vw;
		/* height: 100rpx; */
		padding: 20rpx 40rpx;
		color: #FF4110;
		background-color: white;
		margin-top: 20rpx;
		border-radius: 15rpx;
	}

	.nav {
		.search-box {
			height: 30px;
			width: 400rpx;
			background-color: #fff;
			border-radius: 100px;
			display: flex;
			align-items: center;
			padding: 0 30rpx;

			.left {
				font-size: 14px;
				align-items: center;

				.city {
					margin-right: 2rpx;
				}

				.icon {
					font-size: 28rpx;
				}
			}

			.fenge {
				background-color: #B6B6B6;
				width: 1px;
				height: 24rpx;
				margin: 0 15rpx;
			}

			.right {
				color: rgb(144, 147, 153);
				font-size: 24rpx;
			}
		}
	}

	.tab {
		.filter {
			font-size: 14px;
		}

		.es-filter__expand {
			font-size: 15rpx;
			transition: all 0.3s;
		}
	}
</style>